package models

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"image-build/common"
	"image-build/util"
	"io/ioutil"
	"os"
	"path/filepath"
)

type Build struct{}

//buildimage方法,分三步
//1.dockefile落到指定目录
//2.执行docker build  docker tag
//3. 查出该镜像的子镜像，顺序docker build
func (b *Build) Buildimage(build *TbBuild) error {
	imageName := build.ImageName
	filepath, err := b.WriteDockerfile(build.Dockerfile, imageName)
	if err != nil {
		return err
	}
	err = b.DockerBuild(imageName, filepath)
	if err != nil {
		return err
	}
	return nil
}

//将Dockerfile落到磁盘buildpath路径下
func (b *Build) WriteDockerfile(dockerfile string, imageName string) (string, error) {
	//创建build path,默认是/xxx/xxx/$imageName
	buildPath := fmt.Sprintf(common.BuildPath, imageName)
	if !b.PathIsExist(buildPath) {
		os.MkdirAll(buildPath, os.ModePerm)
	}
	filepath := filepath.Join(buildPath, fmt.Sprintf("Dockerfile-%v", imageName))
	fmt.Printf("filepath=%v", filepath)
	err := ioutil.WriteFile(filepath, []byte(dockerfile), 0644)
	if err != nil {
		logs.Error("write dockerfile %v to %v error", imageName, filepath)
		return filepath, err
	}
	return filepath, nil
}

//封装docker命令
func (b *Build) DockerBuild(imageName string, filepath string) error {
	buildArgs := []string{"build", "-f", filepath, "--pull", "--tag", imageName, "."}
	//buildLog, err := util.RunCommand("docker", buildArgs)
	_, buildLog, err := util.ExecCommond("docker", buildArgs)
	if err != nil {
		//docker build命令有错误返回，更新error日志
		logs.Error("docker build err:%s\n", err)
		if err := UpdateBuildlogByImageName(buildLog, imageName); err != nil {
			logs.Error("database update alert error:%s\n", err)
		}
		return err
	}
	if err := UpdateBuildlogByImageName(buildLog, imageName); err != nil {
		logs.Error("database update alert error:%s\n", err)
	}

	return nil
}

func (b *Build) PathIsExist(path string) bool {
	_, err := os.Stat(path)
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		if os.IsNotExist(err) {
			return false
		}
		fmt.Println(err)
		return false
	}
	return true
}
